<!DOCTYPE HTML>
<html>
<script src='test.js'></script>
<script src='execute_async_script.js'></script>
<script>

function testUserScriptThrows(runner) {
  executeAsyncScript('f(123);', [], true).then((result)=>{
    assertEquals(StatusCode.JAVASCRIPT_ERROR, result.status);
    runner.continueTesting();
    });
  runner.waitForAsync("StatusCode.JAVASCRIPT_ERROR");
}

function testScriptThrows(runner) {
  executeAsyncScript('f(123);', [], false).then((result)=>{
    assertEquals(StatusCode.UNKNOWN_ERROR, result.status);
    runner.continueTesting();
    });
  runner.waitForAsync("StatusCode.UNKNOWN_ERROR");
}

function testUserScriptWithArgs(runner) {
  let injectedArgs = null;
  function captureArguments(args) {
    injectedArgs = args;
  }
  // Pass function captureArguments as the first argument. It is used to capture
  // the injected arguments to the following script.
  const script =
      'var args = arguments; args[0](args); args[args.length - 1](args[1]);';
  const script_args = [captureArguments, 1];
  executeAsyncScript(script, script_args, true)
    .then((result)=>{
      assertEquals(3, injectedArgs.length);
      assertEquals(captureArguments, injectedArgs[0]);
      assertEquals(1, injectedArgs[1]);

      assertEquals(0, result.status);
      assertEquals(1, result.value);
      runner.continueTesting();
    });
  runner.waitForAsync("arguments are captured");
}

function testNonUserScriptCallback(runner) {
  executeAsyncScript('arguments[1](arguments[0])', [33], false)
    .then((result)=>{
      assertEquals(0, result.status);
      assertEquals(33, result.value);
      runner.continueTesting();
    });
  runner.waitForAsync('user script callback');
}

function testNonUserScriptCustomError(runner) {
  executeAsyncScript('arguments[2](new Error("ERR"))', [33], false)
    .then((result)=>{
      assertEquals(StatusCode.UNKNOWN_ERROR, result.status);
      assertEquals(0, result.value.indexOf('ERR'));
      runner.continueTesting();
    });
  runner.waitForAsync("custom error");
}

function testNonUserScriptCustomErrorCode(runner) {
  executeAsyncScript('var e = new Error("ERR"); e.code = 111; arguments[1](e)',
    [], false).then((result)=>{
      assertEquals(111, result.status);
      assertEquals(0, result.value.indexOf('ERR'));
      runner.continueTesting();
  });
  runner.waitForAsync("custom error with custom error code");
}

</script>
<body>
</body>
</html>
